﻿using System;
using System.Security.Principal;
using System.Web;
using AspNet.Identity.DataAccess;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using MvcApplication.Common;


namespace MvcApplication.Identity
{
    public class IdentityUserManager : UserManager<IdentityUser, Guid>
    {
        protected IdentityUserManager(IUserStore<IdentityUser, Guid> store) : base(store) { }

        public static Guid GetUserId(IPrincipal user)
        {
            Guid userId;
            if (user.Identity.Name.TryParseGuid(out userId))
            {
                return userId;
            }
            throw new Exception("Not a valid userid");
        }

        public static IdentityUserManager GetManager()
        {
            IdentityUserManager userManager = null;

            var owinContext = HttpContext.Current.GetOwinContext();
            if (owinContext != null)
            {
                userManager = owinContext.GetUserManager<IdentityUserManager>();
            }

            // Fallback if OWIN application code removed from project
            if (userManager == null)
            {
                userManager = new IdentityUserManager(new UserStore());
            }

            return userManager;
        }
    }
}
